package ru.magicreader.server.model;

import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.sun.syndication.feed.synd.SyndFeed;

/*
 * Feed the User is subscribed to.
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Feed implements Serializable {
	private static final long serialVersionUID = 1L;

	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;

	@Persistent
	private String url;
	
	@Persistent
	private String title;
	
	@Persistent
	private Boolean isValid = true;
	
	@Persistent
	private Boolean isImportant;
	
	@Persistent
	private LinkedList<Date> readEntryDatesList = new LinkedList<Date>();
	
	@NotPersistent
	private SyndFeed internal;
	
	public Feed(String url, boolean isImportant) {
		this.url = url;
		this.isImportant = isImportant;
	}

	public Key getId() {
		return id;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setValid(boolean isValid) {
		this.isValid = isValid;
	}

	public boolean isValid() {
		return isValid != null && isValid.booleanValue();
	}
	
	public void setImportant(boolean isImportant) {
		this.isImportant = isImportant;
	}

	public boolean isImportant() {
		return isImportant != null && isImportant.booleanValue();
	}

	public void addReadEntryDate(Date date) {
		readEntryDatesList.add(date);
		
		//reduce the number of records to 10
		while(readEntryDatesList.size() > 10) {
			readEntryDatesList.removeFirst();
		}
	}
	
	public List<Date> getReadEntryDates() {
		return readEntryDatesList;
	}

	public void setInternal(SyndFeed internal) {
		this.internal = internal;
	}

	public SyndFeed getInternal() {
		return internal;
	}

	public String toJson() {
		return "{\n" +
			"\"url\": \"" + url + "\",\n" +
			"\"title\": \"" + title + "\",\n" +
			"\"valid\": " + isValid() + ",\n" +
			"\"important\": " + isImportant() + "\n" +
		"}\n";
	}
}
